﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using RuoVea.ExConfig;
using RuoVea.ExEnum;
using RuoVea.ExFilter;
using RuoVea.ExIdGen;
using RuoVea.ExJwtBearer;
using RuoVea.ExUtil;

namespace KeGie.Admin.Entry.Controllers
{
    /// <summary>
    /// Swagger 鉴权
    /// </summary>
    [ApiController]
    [Route("[controller]")]
    [ApiExplorerSettings(GroupName = "KeGie.Admin.Doc")]
    public class SwaggerAuthController : ControllerBase
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IJwtHelper _jwtHelper;

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="httpContextAccessor"></param>
        /// <param name="jwtHelper"></param>
        public SwaggerAuthController(IHttpContextAccessor httpContextAccessor, IJwtHelper jwtHelper)
        {
            _httpContextAccessor = httpContextAccessor;
            _jwtHelper = jwtHelper;
        }

        /// <summary>
        /// Swagger登录检查 🔖
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [NonRestfulResult]
        [HttpPost("/api/swagger/checkUrl")]
        public int SwaggerCheckUrl()
        {
            return _httpContextAccessor.HttpContext.User.Identity.IsAuthenticated ? 200 : 401;
        }

        /// <summary>
        /// Swagger登录提交 🔖
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [NonRestfulResult]
        [HttpPost("/api/swagger/submitUrl")]
        public int SwaggerSubmitUrl([FromForm] string userName, [FromForm] string password)
        {
            try
            {
                if (userName.IsNullOrWhiteSpace() || password.IsNullOrWhiteSpace())
                    return 401;

                // todo  此步骤可以直接对接数据库
                string? setUserName = AppSettings.GetValue("Swagger", "LoginInfo", "UserName")?.ToString();
                string? setPassword = AppSettings.GetValue("Swagger", "LoginInfo", "Password")?.ToString();

                if (setUserName == userName&& password== setPassword)
                {
                    // 生成 Token 或设置认证 Cookie
                    var token = _jwtHelper.CreateToken(new UserVo
                    {
                        Id = IdGenerator.Id,
                        Account = userName,
                        Name = "Swagger User",
                        AdminType = AdminType.SuperAdmin.ToString()
                    });
                    // 设置 Swagger 自动登录
                    _httpContextAccessor.HttpContext.SigninToSwagger(token);
                    return 200;
                }
                else
                {
                    return 401;
                }
            }
            catch (Exception)
            {
                return 401;
            }
        }
    }
}
